﻿using System.Collections.Generic;
using ShureValidation.Rules;

namespace ShureValidation.Language
{
    /// <summary>
    /// Loads language from attributes.
    /// </summary>
    internal class RuleLanguage : IModelLanguage
    {
        private readonly ILanguagePrompts _prompts;
        private readonly string _modelName;
        private static readonly Dictionary<string, string> _translations = new Dictionary<string, string>();

        /// <summary>
        /// Initializes a new instance of the <see cref="RuleLanguage"/> class.
        /// </summary>
        /// <param name="prompts">The prompts.</param>
        public RuleLanguage(ILanguagePrompts prompts)
        {
            _prompts = prompts;
        }

        /// <summary>
        /// Gets or sets current rule
        /// </summary>
        public IRule Rule { get; set; }

        /// <summary>
        /// Gets language prompt
        /// </summary>
        /// <value></value>
        /// <returns>Translation if found; otherwise "[promptName]" without the quotes.</returns>
        public string this[string promptName]
        {
            get
            {
                var prompt = _prompts.Get(_modelName, promptName);
                if (prompt != null)
                    return prompt;
                
                lock (_translations)
                {
                    if (_translations.TryGetValue(promptName, out prompt))
                        return prompt;

                    var attributes = Rule.GetType().GetCustomAttributes(typeof (LanguagePromptAttribute), true);
                    foreach (var attribute in attributes)
                    {
                        var attr = (LanguagePromptAttribute) attribute;
                        _translations[attr.Name] = attr.Prompt;
                    }
                }

                return _translations.TryGetValue(promptName, out prompt) ? prompt : string.Empty;
            }
        }
    }
}